import { Context, Next } from 'hono';
import { AuthController } from '../controllers/AuthController';

const authController = new AuthController();

export const authMiddleware = async (c: Context, next: Next) => {
  try {
    const authHeader = c.req.header('Authorization');
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return c.json({
        success: false,
        error: 'Unauthorized',
        message: 'No token provided',
      }, 401);
    }

    const token = authHeader.substring(7); // Remove 'Bearer ' prefix
    const user = await authController.verifyToken(token);

    if (!user) {
      return c.json({
        success: false,
        error: 'Unauthorized',
        message: 'Invalid or expired token',
      }, 401);
    }

    // 将用户信息添加到上下文
    c.set('user', user);
    
    await next();
  } catch (error) {
    console.error('Auth middleware error:', error);
    return c.json({
      success: false,
      error: 'Unauthorized',
      message: 'Authentication failed',
    }, 401);
  }
};

// 管理员权限中间件
export const adminMiddleware = async (c: Context, next: Next) => {
  const user = c.get('user');
  
  if (!user || !user.isAdmin()) {
    return c.json({
      success: false,
      error: 'Forbidden',
      message: 'Admin access required',
    }, 403);
  }

  await next();
};

// 权限检查中间件工厂
export const permissionMiddleware = (permission: string) => {
  return async (c: Context, next: Next) => {
    const user = c.get('user');
    
    if (!user || !user.hasPermission(permission)) {
      return c.json({
        success: false,
        error: 'Forbidden',
        message: `Permission '${permission}' required`,
      }, 403);
    }

    await next();
  };
};
